<template>
	<view class="">
		<view class="file-list">
			<view class="item" v-for="(item, index) in fileList" :key="index" @click="onSelect(item.path, item.name)">
				<view class="" style="display: flex;align-items: center;">
					<view class="left">
						<!-- #ifdef H5 -->
						<view class="l-icons" :class="[getImageUrl(item.name)]" :style="{color:getColor(item.name)}"></view>
						<!-- #endif -->
						<!-- #ifdef APP -->
						<view class="l-icons" :class="[getImageUrl(item.fileName)]" :style="{color:getColor(item.fileName)}"></view>
						<!-- #endif -->
					</view>
					<view class="right">
						<!-- #ifdef H5 -->
						<view class="file-name" style="overflow: hidden;">{{ item.name }}</view>
						<!-- #endif -->
						<!-- #ifdef APP -->
						<view class="file-name" style="overflow: hidden;">{{ item.fileName }}</view>
						<!-- #endif -->
					</view>
				</view>
				<view class="l-icons icon-jian" style="font-size: 40rpx;color: #666666;padding: 0 10rpx;" v-if="showClose"
					@tap.stop="deleteFile(index)"></view>
			</view>
		</view>
		<!-- #ifdef H5 -->
		<button @click="chooseFile" style="font-size: 30rpx;background-color: #FF6F30;color: #fff;width:200rpx" v-if="!fileList.length">上传附件</button>
		<!-- #endif -->
		
		<!-- #ifdef APP -->
		<view class="box-lsj-upload" >
			<lsj-upload
			ref="lsjUpload0"
			childId="upload1"
			:width="width"
			:option="option"
			:size="size"
			:count="count"
			:formats="formats"
			:debug="debug"
			:instantly="instantly"
			@change="onChange"
			@progress="onprogress"
			@uploadEnd="onuploadEnd"
			v-if="!fileList.length">
				<button style="font-size: 30rpx;background-color: #FF6F30;color: #fff;width:200rpx" >上传附件</button>
			</lsj-upload>
		</view>
		<!-- #endif -->
		
	</view>
</template>
<script>
	import http from "../../../../common/http.js"
	export default {
		name: 'lAnnexFile',
		props: {
			//服务器接口地址。当接口地址为空时，直接返回本地文件
			serverUrl: {
				type: String,
				default: http.baseUrl + '/common/uploadFile'
			},
			//HTTP 请求 Header, header 中不能设置 Referer。
			header: {
				type: Object,
				default () {
					return {}
				}
			},
			//HTTP 请求中其他额外的 form data
			formData: {
				type: Object,
				default () {
					return {}
				}
			},
			//是否显示删除按钮 默认是
			showClose: {
				type: Boolean,
				default: true
			},
		},
		data() {
			return {
				fileList: [],
				//app端选择文件的参数
				option: {
					// 上传服务器地址，需要替换为你的接口地址
					url: http.baseUrl + '/common/uploadFile', // 该地址非真实路径，需替换为你项目自己的接口地址
					// 上传附件的key
					name: 'file',
					// 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
					header: {
						// 示例参数可删除
						'Authorization': 'bearer aa',
						'uid': '27',
						'accountid': '27'
					},
					// 根据你接口需求自定义body参数
					formData: { 
						// 'orderId': 1000
					}
				},
				// 选择文件后是否立即自动上传，true=选择后立即上传
				instantly: true,
				// 必传宽高且宽高应与slot宽高保持一致
				width: '200rpx',
				// 限制允许上传的格式，空串=不限制，默认为空
				formats: '',
				// 文件上传大小限制
				size: 30,
				// 文件数量限制
				count: 2,
				// 是否多选
				multiple: true,
				// 文件回显列表
				files: new Map(),
				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				wxFiles: [],
				// 是否打印日志
				debug: true,
				// 演示用
				tabIndex: 0,
				
				list:[], 
			}
		},
		methods: {
			change() {
				this.$emit('complete', {
					fileList: [...this.fileList],
				})
			},
			getImageUrl(name) {
				console.log(name)
				// return name => {
				if (!name) return
				console.log(name)
				let type = name.split('.');
				type = type[type.length - 1];
				if (type === 'doc' || type === 'docx') {
					return `icon-file_word`;
				} else if (type === 'pdf') {
					return `icon-pdf`;
				} else if (type === 'jpeg' || type === 'png' || type === 'jpg' || type === 'gif' || type ===
					'svg') {
					return `icon-jpg`;
				} else if (type === 'xlsx' || type === 'xls') {
					return `icon-xls`;
				} else if (type === 'zip' || type === 'rar') {
					return `icon-file-zip`;
				} else if (type === 'txt') {
					return `icon-wenjian_txt`;
				} else if (type === 'ppt' || type === 'pptx') {
					return `icon-file_ppt`;
				} else if (type === 'mp4') {
					return `icon-mp4`;
				}
				// };
			},
			getColor(name) {
				if (!name) return
				console.log(name)
				let type = name.split('.');
				type = type[type.length - 1];
				if (type === 'doc' || type === 'docx') {
					return `#57A7FF`;
				} else if (type === 'pdf') {
					return `#FF6464`;
				} else if (type === 'jpeg' || type === 'png' || type === 'jpg' || type === 'gif' || type ===
					'svg') {
					return `#FFD773`;
				} else if (type === 'xlsx' || type === 'xls') {
					return `#1FB77A`;
				} else if (type === 'zip' || type === 'rar') {
					return `#7DB4FF`;
				} else if (type === 'txt') {
					return `#666666`;
				} else if (type === 'ppt' || type === 'pptx') {
					return `#FF917B`;
				} else if (type === 'mp4') {
					return `#FFC466`;
				}
			},
			chooseFile() {
				// #ifdef H5
				wx.chooseFile({
					count: 1,
					type: 'all',
					success: (res) => {
						const tempFilePaths = res.tempFiles
						for (let i = 0; i < tempFilePaths.length; i++) {
							this.fileList.push(tempFilePaths[i])
							//服务器地址
							if (this.serverUrl) {
								this.upload(i, tempFilePaths[i]).then(() => {
									this.change()
								}).catch(() => {
									this.change()
								})
							} else {
								//无服务器地址则直接返回成功
								this.change()
							}
						}
					}
				})
				setTimeout(()=>{
					console.log('this.fileList',this.fileList)
				},500)
				// #endif
			},
			upload(index, url) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.serverUrl,
						name: 'file',
						header: this.header,
						formData: {
							fileName: url.name,
							...this.formData
						},
						filePath: url.path,
						success: (res) => {
							if (res.statusCode == 200) {
								console.log("res",res.data)
								//返回结果 此处需要按接口实际返回进行修改
								this.fileList[index] = JSON.parse(res.data) //根据实际情况修改
								
								this.$emit('callback',JSON.parse(res.data))
								resolve()
							} else {
								reject(res.msg)
							}
						},
						fail: function(res) {
							console.log(res)
							reject(res)
						}
					})
				})

			},

			deleteFile(index) {
				uni.showModal({
					title: '提示',
					content: '确定删除该文件吗？',
					success: (res) => {
						if (res.confirm) {
							this.fileList.splice(index, 1)
						}
					}
				})
			},
			// 预览文件
			onSelect(filePath, fileName) {
				return false
				let type = fileName.split('.');
				type = type[type.length - 1]
				let str = 'doc, xls, ppt, pdf, docx, xlsx, pptx';
				let self = this;
				console.log(str.indexOf(type) >= 0);
				if (str.indexOf(type) >= 0) {
					uni.showLoading()
					console.log(filePath);
					this.downloadTask = uni.downloadFile({
						url: filePath,
						success: function(res) {
							uni.hideLoading()
							var filePath = res.tempFilePath;
							uni.openDocument({
								filePath: filePath,
								showMenu: true,
								success: function(res) {
									console.log('打开文档成功');
								}
							});
						}
					});
				} else if (type === 'jpeg' || type === 'png' || type === 'jpg' || type === 'gif' || type === 'svg') {
					uni.previewImage({
						urls: [filePath]
					});
				} else {
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '该文件不支持预览',
						duration: 3000
					});
				}
			},
			// app时文件上传
			 onChange(files) {
				// console.log('当前选择的文件列表：',JSON.stringify([...files.values()]));
				// // 更新选择的文件 
				// this.files = files;
				// // 强制更新视图
				// this.$forceUpdate();
			},
			// 上传进度回调
			onprogress(item) {
				// // 更新当前状态变化的文件
				// this.files.set(item.name,item);
				
				// console.log('打印对象',JSON.stringify(this.files.get(item.name)));
				// // 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// // #ifdef MP-WEIXIN
				// this.wxFiles = [...this.files.values()];
				// // #endif
				
				// // 强制更新视图
				// this.$forceUpdate();
				
			},
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				this.fileList[0] = JSON.parse(item.responseText).data
				console.log(this.fileList)
				this.$emit('callback',JSON.parse(item.responseText))
				this.$forceUpdate()
			},
		}
	}
</script>
<style lang="scss" scoped>
	@font-face {
		font-family: 'l-icons';
		src: url('data:font/ttf;charset=utf-8;base64,AAEAAAANAIAAAwBQRkZUTZbXywEAAA4UAAAAHEdERUYAKQASAAAN9AAAAB5PUy8yPDVJwQAAAVgAAABgY21hcLOFndYAAAHYAAABcmdhc3D//wADAAAN7AAAAAhnbHlmcbkKtwAAA2gAAAeIaGVhZCRL5/UAAADcAAAANmhoZWEHpgOFAAABFAAAACRobXR4DfsB+wAAAbgAAAAgbG9jYQkwBy4AAANMAAAAGm1heHABI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HxphkyccHCknHR0WXF0GDwILDQgIBAQDAQgPCw4KDQcIAwQDAQQEBhUOAAAAAAsAbv+AA5IDgAARABQAGAAcACAAJAAoACwAMAA0ADgAAAEWFREUBiMhIiY1ETQ2MyEyFxMnFSUVMzUdATM1BxUzNR0BMzUHFTM1HQEzNQcVMzUHFTM1BzMVIwOIChUP/SQPFRUPAeYPC6zX/qJJSZJJSZJJSZJJSZJbJSUCfwsP/UAQFRUQA7YQFQv+4NfX2UlJSUpKSklJSUlJSUlJSUlJSUlJSbe3N0kAAAAAABIA3gABAAAAAAAAABMAKAABAAAAAAABAAgATgABAAAAAAACAAcAZwABAAAAAAADAAgAgQABAAAAAAAEAAgAnAABAAAAAAAFAAsAvQABAAAAAAAGAAgA2wABAAAAAAAKACsBPAABAAAAAAALABMBkAADAAEECQAAACYAAAADAAEECQABABAAPAADAAEECQACAA4AVwADAAEECQADABAAbwADAAEECQAEABAAigADAAEECQAFABYApQADAAEECQAGABAAyQADAAEECQAKAFYA5AADAAEECQALACYBaABDAHIAZQBhAHQAZQBkACAAYgB5ACAAaQBjAG8AbgBmAG8AbgB0AABDcmVhdGVkIGJ5IGljb25mb250AABpAGMAbwBuAGYAbwBuAHQAAGljb25mb250AABSAGUAZwB1AGwAYQByAABSZWd1bGFyAABpAGMAbwBuAGYAbwBuAHQAAGljb25mb250AABpAGMAbwBuAGYAbwBuAHQAAGljb25mb250AABWAGUAcgBzAGkAbwBuACAAMQAuADAAAFZlcnNpb24gMS4wAABpAGMAbwBuAGYAbwBuAHQAAGljb25mb250AABHAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAHMAdgBnADIAdAB0AGYAIABmAHIAbwBtACAARgBvAG4AdABlAGwAbABvACAAcAByAG8AagBlAGMAdAAuAABHZW5lcmF0ZWQgYnkgc3ZnMnR0ZiBmcm9tIEZvbnRlbGxvIHByb2plY3QuAABoAHQAdABwADoALwAvAGYAbwBuAHQAZQBsAGwAbwAuAGMAbwBtAABodHRwOi8vZm9udGVsbG8uY29tAAAAAAIAAAAAAAAACgAAAAAAAQAAAAAAAAAAAAAAAAAAAAAADAAAAAEAAgECAQMBBAEFAQYBBwEIAQkBCgRqaWFuC3dlbmppYW5fdHh0A3BkZghmaWxlX3BwdAlmaWxlX3dvcmQDanBnA21wNAN4bHMIZmlsZS16aXAAAAAAAf//AAIAAQAAAAwAAAAWAAAAAgABAAMACwABAAQAAAACAAAAAAAAAAEAAAAA1aQnCAAAAADgmdH8AAAAAOCZ0fw=') format('truetype');
		font-weight: normal;
		font-style: normal;
		font-display: swap;
	}

	.l-icons {
		font-family: "l-icons" !important;
		font-size: 80rpx;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	.icon-jpg:before {
		content: "\e6a0";
	}

	.icon-pdf:before {
		content: "\e616";
	}

	.icon-file_ppt:before {
		content: "\e699";
	}

	.icon-file_word:before {
		content: "\e69a";
	}

	.icon-file-zip:before {
		content: "\e6f2";
	}

	.icon-jian:before {
		content: "\e600";
	}

	.icon-wenjian_txt:before {
		content: "\e60e";
	}

	.icon-mp4:before {
		content: "\e6a1";
	}

	.icon-xls:before {
		content: "\e6a4";
	}

	.item {
		padding: 20rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.left {
			padding-right: 20rpx;
		}

		.right {
			font-size: 28rpx;

			.file-name {
				word-break: break-all;
				/* break-all(允许在单词内换行。) */
				text-overflow: ellipsis;
				/* 超出部分省略号 */
				display: -webkit-box;
				/** 对象作为伸缩盒子模型显示 **/
				-webkit-box-orient: vertical;
				/** 设置或检索伸缩盒对象的子元素的排列方式 **/
				-webkit-line-clamp: 2;
				/** 显示的行数 **/
				
			}

			.size {
				color: #909399;
				padding-top: 10rpx;
				font-size: 24rpx;
			}
		}
	}
	
	.box-lsj-upload{
		position: relative;
		z-index: 4;
	}
</style>
